package com.umeox.calculator;

import android.text.Editable;
import android.text.SpannableStringBuilder;

class CalculatorEditable extends SpannableStringBuilder {
    private static final char[] ORIGINALS = {'-', '*', '/'};
    private static final char[] REPLACEMENTS = {8722, 215, 247};
    private boolean isInsideReplace;
    private Logic mLogic;

    private CalculatorEditable(CharSequence source, Logic logic) {
        super(source);
        this.isInsideReplace = false;
        this.mLogic = logic;
    }

    @Override // android.text.SpannableStringBuilder, android.text.SpannableStringBuilder
    public SpannableStringBuilder replace(int start, int end, CharSequence tb, int tbstart, int tbend) {
        if (this.isInsideReplace) {
            return super.replace(start, end, tb, tbstart, tbend);
        }
        this.isInsideReplace = true;
        try {
            return internalReplace(start, end, tb.subSequence(tbstart, tbend).toString());
        } finally {
            this.isInsideReplace = false;
        }
    }

    private SpannableStringBuilder internalReplace(int start, int end, String delta) {
        if (!this.mLogic.acceptInsert(delta)) {
            this.mLogic.cleared();
            start = 0;
            end = length();
        }
        for (int i = ORIGINALS.length - 1; i >= 0; i--) {
            delta = delta.replace(ORIGINALS[i], REPLACEMENTS[i]);
        }
        if (delta.length() == 1) {
            char text = delta.charAt(0);
            if (text == '.') {
                int p = start - 1;
                while (p >= 0 && Character.isDigit(charAt(p))) {
                    p--;
                }
                if (p >= 0 && charAt(p) == '.') {
                    return super.replace(start, end, (CharSequence) "");
                }
            }
            char prevChar = start > 0 ? charAt(start - 1) : 0;
            if (text == 8722 && prevChar == 8722) {
                return super.replace(start, end, (CharSequence) "");
            }
            if (Logic.isOperator(text)) {
                while (Logic.isOperator(prevChar) && (text != 8722 || prevChar == '+')) {
                    start--;
                    prevChar = start > 0 ? charAt(start - 1) : 0;
                }
            }
            if (start == 0 && Logic.isOperator(text) && text != 8722) {
                return super.replace(start, end, (CharSequence) "");
            }
        }
        return super.replace(start, end, (CharSequence) delta);
    }

    public static class Factory extends Editable.Factory {
        private Logic mLogic;

        public Factory(Logic logic) {
            this.mLogic = logic;
        }

        public Editable newEditable(CharSequence source) {
            return new CalculatorEditable(source, this.mLogic);
        }
    }
}
